import React from 'react';
import { Card, Row, Col, Table } from 'antd';
import { model } from 'utils/model';
import Page from 'components/common/Page';
import { nextTick } from 'utils/nextTick';
import echarts from 'echarts/lib/echarts';
import 'echarts/lib/chart/bar';
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import moment from 'moment';
import { queryRealTimeMonitorData } from 'services/chart';
import { combineDate } from 'utils/share';
import Polyline from './Polyline';
import fields from './fields';
import SearchBar from './SearchBar';
import styles from './index.less';

let myChart = null;

const initOption = (arr = [], record) => {
  const yVal = [];
  const xVal = [];
  arr.forEach(item => {
    yVal.push(item.val);
    xVal.push(item.name);
  });
  return {
      title: {
        text: `设备名称：${record.name}`,
        x: 'center',
        top: '10px',
        textStyle: {
          width: '100%',
          fontWeight: 'normal',
          fontSize: 15
        }
      },
      xAxis: {
          type: 'category',
          data: xVal
      },
      grid: {
        top: 50,
        bottom: 70
      },
      yAxis: {
          type: 'value',
          boundaryGap: ['20%', '20%'],
          axisLine: {
            lineStyle: {
              color: '#555'
            }
          }
      },
      series: [{
          data: yVal,
          type: 'bar',
          barWidth: '40%',
          itemStyle: {
            color: '#1890ff',
            barBorderRadius: [5, 5, 0, 0] //（顺时针左上，右上，右下，左下）
          },
          axisLine: {
            lineStyle: {
              color: '#e8e8e8'
            }
          },
          label: { 
            show: true,
            position: 'top',
            color: '#000'
          }
      }]
  };
};

@model('dashMonitor')
class DashMonitor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: moment(),
      record: {} // 当前设备
    };
    this.setRowClassName = this.setRowClassName.bind(this);
  }

  componentDidMount(){
    myChart = echarts.init(document.getElementById('main'));
    
  }
  getEquipent(equipmentNo, item){
    if(item){
      queryRealTimeMonitorData({ deviceNo: equipmentNo }).then(({ data }) => {
        if(data){
          const option = initOption(data, item);
          myChart.setOption(option);
        }else{
          const option = initOption([], item);
          myChart.setOption(option);
        }
      });
      const { queryTimeRangeGps } = this.props;
      const { value } = this.state;
      if(value){
        const params = combineDate([ value, value ]);
        queryTimeRangeGps({ deviceNo: item.equipmentNo, ...params });
      }
    }
    if(!item.longitude && !item.latitude){
      const point = new window.BMap.Point(116.404, 39.915);
      this.map.centerAndZoom(point, 9);
      this.map.enableScrollWheelZoom(true);
    }
    
  }
  // init Point
  initPoint(item){
    this.map.clearOverlays();      
    const { longitude, latitude } = item;
    const geoc = new window.BMap.Geocoder();
    if(longitude && latitude){
      const point = new window.BMap.Point(longitude, latitude);
      this.map.centerAndZoom(point, 9);
      this.map.enableScrollWheelZoom(true);
      const po = new window.BMap.Point(longitude, latitude);
      // itArr.push(po);
      var marker = new window.BMap.Marker(po);
      this.map.addOverlay(marker);
      geoc.getLocation(po, (res) => {
        if(res && res.address){
          var opts = {
            width : 200,     // 信息窗口宽度
            height: 100,     // 信息窗口高度
            title : "详细位置" , // 信息窗口标题
            enableMessage: true//设置允许信息窗发送短息
          };
          var infoWindow = new window.BMap.InfoWindow(`设备名称：${item.name}</br>地址：${res.address}`, opts);  // 创建信息窗口对象 
          marker.addEventListener("click", function(){          
            this.map.openInfoWindow(infoWindow, po, item); //开启信息窗口
          });
          this.map.openInfoWindow(infoWindow, po, item); //开启信息窗口
        }
      });
    }
  }

  componentWillReceiveProps(next){
    if(next.config.list !== this.props.config.list){
      nextTick(() => {
        this.map = new window.BMap.Map('myMap');
        const data = next.config.list || [];
        if(data.length){
          const item = data.find(item => item.longitude && item.latitude) || {};
          this.initPoint(item);
          const { equipmentNo } = item;
          this.setState({ record: item });
          if(equipmentNo){
            this.getEquipent(equipmentNo, item);
          }
          }else{
            const point = new window.BMap.Point(116.404, 39.915);
            this.map.centerAndZoom(point, 9);
            this.map.enableScrollWheelZoom(true);
          }
          
      });
    }
  }

  openInfoWindow(longitude, latitude, row){
    const po = new window.BMap.Point(longitude, latitude);
    const geoc = new window.BMap.Geocoder();
    geoc.getLocation(po, (res) => {
      if(res && res.address){
        var opts = {
          width : 200,     // 信息窗口宽度
          height: 100,     // 信息窗口高度
          title : "详细位置" , // 信息窗口标题
          enableMessage: true//设置允许信息窗发送短息
        };
        var infoWindow = new window.BMap.InfoWindow(`当前设备：${row.name}</br>地址：${res.address}`, opts);  // 创建信息窗口对象 
        this.map.openInfoWindow(infoWindow, po); //开启信息窗口
      }
    });
  }

  setRowClassName(row){
    const { record } = this.state;
    return row.id === record.id ? styles.activeRow : '';
  }

  render() {
    const { 
      config,
      goPage,
      getList,
      loading,
      timeRangeGps,
      queryTimeRangeGps
     } = this.props;
    const { pagination, list } = config;
    const { record, value } = this.state;
    const tableProps = {
      size: "small",
      pagination: {
        ...pagination,
        onChange: (current) => {
          goPage(current);
          getList();
        }
      },
      loading: loading.list,
      rowKey: (record, index) => index,
      dataSource: list,
      columns: fields,
      rowClassName: this.setRowClassName,
      onRow: (record) => {
        return {
          onClick: () => {
            nextTick(() => {
              this.setState({
                record
              });
            });
            const { equipmentNo } = record;
            this.getEquipent(equipmentNo, record);
            this.initPoint(record);
          }
        };
      }
    };
    const searchProps = {
      onSearch: getList
    };
    const polyProps = {
      value,
      record,
      timeRangeGps,
      queryTimeRangeGps,
      updateParent: (params) => this.setState(params)
    };
    return (
      <Page inner>
        <Row gutter={24}>
          <Col span="8">
            <Card
              title={<div>设备列表</div>}
              bodyStyle={{ padding: 0 }}
              style={{ 
                width: '100%', 
                height: 500
              }}
            >
              <SearchBar {...searchProps} />
              <Table {...tableProps} />
            </Card>
            <Card
              className={styles.chartWrap}
              title="设备实时信息"
              bodyStyle={{ padding: 0 }}
              style={{ 
                width: '100%', 
                height: 300,
                marginTop: 20
              }}
            >
              <div 
                id="main" 
                style={{ width: '100%', height: 290 }}
              />
              
            </Card>
          </Col>
          <Col span="16">
            <Card
              title={<div>设备监控</div>}
              style={{ width: '100%', height: 300, position: 'relative' }}
              bodyStyle={{ padding: 0 }}
            >
              <div style={{ width: '100%', height: 250 }} id="myMap" />
            </Card>
            {
              record.id &&
              <Polyline {...polyProps} />
            }
          </Col>
        </Row>
      </Page>
    );
  }
}

export default DashMonitor;
